<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //若 obj1 的 pid === obj 的 id 则 obj1 是 obj 的子级
        //  obj { .....   obj1{}...obj2...}
        const data = [
            { id: "01", name: "张大大", pid: "", job: "项目经理" },

            { id: "02", name: "小亮", pid: "01", job: "产品leader" },
            { id: "07", name: "小丽", pid: "02", job: "产品经理" },
            { id: "08", name: "大光", pid: "02", job: "产品经理" },

            { id: "03", name: "小美", pid: "01", job: "UIleader" },
            { id: "09", name: "小高", pid: "03", job: "UI设计师" },
            { id: "05", name: "老王", pid: "01", job: "测试leader" },
            { id: "06", name: "老李", pid: "01", job: "运维leader" },

            { id: "04", name: "老马", pid: "01", job: "技术leader" },
            { id: "10", name: "小刘", pid: "04", job: "前端工程师" },
            { id: "11", name: "小华", pid: "04", job: "后端工程师" },
            { id: "12", name: "小李", pid: "04", job: "后端工程师" },

            { id: "13", name: "小赵", pid: "05", job: "测试工程师" },
            { id: "14", name: "小强", pid: "05", job: "测试工程师" },
            { id: "15", name: "小涛", pid: "06", job: "运维工程师" }
        ]
        // dataList === data 是需要遍历的偏平数组
        function arrToTree(dataList) {

            //定义一个最终需要返回的树形结构数据
            const treeData = []

            //对传入的数组进行遍历 -item -->obj
            dataList.forEach(item => {
                
                //查找 是否是顶级（祖先树节点有pid字段），若是顶级，直接加到 treeData
                if(!item.pid){
                    //item.pid :'' --- false，有值-true
                    treeData.push(item)
                }
                
                //查找子级需要 dataList 每一项进行对比
                //对比关系：每一项的 pid 是否 等于 当前项的 id
                // 当前 item 向数组里查找遍历--查看子级数组的pid 与当前item的 ID 是否相同
              const children = dataList.filter(data => data.pid === item.id) //返回一个符合逻辑的数组

              //查看 children 是否有子级，
              //如果没有，不做处理,跳出此次遍历，进行下一项遍历。 children = [] -children.length === 0 --> false
              if(!children.length) return
              //子级里面还有子级 children = [{...}] 有数据
              item.children = children //给 item 对象 添加一个children 字段--->子级对象
            });

            //返回树形结构的数组 有 children
            return treeData
        }

        // 目标：
        const treeData = arrToTree(data) //已有数组-传参
        console.log(treeData);
    </script>
</body>

</html>